package com.common.android.utils.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

public class SqlStringHelper {
	private final static  String BLACKSPACE=" ";
	public static String getCreateTableString(String tableName,String[] columnNames,String[] columnDefines){
		if (columnDefines==null || columnNames==null || TextUtils.isEmpty(tableName)){
			return null;
		}
		if (columnDefines.length!=columnNames.length){
			return null;
		}
		String sql="create table "+tableName+" (";
		for  (int i=0,len=columnDefines.length;i<len;i++){
			if (i==len-1){
				sql+=columnNames[i]+" "+columnDefines[i]+" )";
			}else{
				sql+=columnNames[i]+" "+columnDefines[i]+" ,";
			}
		}
		return sql;
	}
	
	public static  String getCreateIndexString(String tableName,String indexName,String[] columnNames){
		if (columnNames==null || TextUtils.isEmpty(tableName) || TextUtils.isEmpty(indexName)){
			return null;
		}
		String sql="create index "+tableName+indexName+" on "+tableName+ " (";
		for  (int i=0,len=columnNames.length;i<len;i++){
			if (i==len-1){
				sql+=columnNames[i]+" )";
			}else{
				sql+=columnNames[i]+" ,";
			}
		}
		return sql;
	}
	
	public static String getAlterColumnString(String tableName,String columnName,String columnDefine){
		String sql="alter table "+tableName+" add "+columnName+" "+columnDefine;
		return sql;
	}
	
	
	/**
	 * 
	 * @n<b>函数名称</b>     :checkExistColumn
	 * @brief                查询表是否存在字段
	 * @see 
	 * @since    Ver 1.1
	 * @param  @param db
	 * @param  @param tableName
	 * @param  @param columnName
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  zhy
	 * @<b>创建时间</b>      :  2014-5-13下午2:51:36
	 */
	public static boolean isExistColumn(SQLiteDatabase db,String tableName,String columnName){
		boolean exist=false;
		String sql=String.format("select * from %s  limit 0",tableName);
		Cursor cursor=null;
		try{
			cursor=db.rawQuery(sql, null);
			exist=(cursor!=null&&cursor.getColumnIndex(columnName)!=-1);
		}catch(Exception e){
			e.printStackTrace();
	    }finally{
	    	closeCrusor(cursor);
	    }
		return exist;
	}
	
	public static void closeCrusor(Cursor cursor){
		if (cursor!=null){
			cursor.close();
		}
	}
}
